class User < ActiveRecord::Base
  has_many :novel
  has_many :fragment
  has_many :vote
  has_many :comment

  validates_presence_of :name
  validates_presence_of :mail
  validates_presence_of :password, :if=>Proc.new { |user| user.hashed_password.nil? }
  validates_uniqueness_of :name
  validates_uniqueness_of :mail

  validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i,:allow_nil=>true,:allow_blank=>true
  validates_format_of :name, :on=>:create, :with => /[\w]{3,12}/i,:allow_nil=>true,:allow_blank=>true
  validates_format_of :password, :on=>:create, :with => /[\w]{6,12}/i,:allow_nil=>true,:allow_blank=>true

  attr_accessor :password_confirmation
  validates_confirmation_of :password

  def validate
    #errors.add_to_base("请给定你在本站的密码") if hashed_password.blank?
  end
  
  #'password is a virtual attribute

  def password
    @password
  end

  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password, self.salt)
  end
  
  def fake_password
	@passowrd='fake'
  end

  def self.authenticate(name, password)
    user = self.find_by_name name
    if user
      excepted_password = encrypted_password(password, user.salt)
      if user.hashed_password != excepted_password
        user = nil
      end
    end
    user
  end

  private
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt # Wibble makes it harder to guess
    Digest::SHA1.hexdigest(string_to_hash)
  end

  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end

end
